<template>
  <view>
    <form>
      <xmInfo
      :projectno="dataInfo.projectno"
      :projectname="dataInfo.projectname"
    ></xmInfo>
    <!--  <view class="cu-card margin radius">
       
        <view class="cu-form-group">
          <view class="title">巡检人</view>
          <view>{{ dataInfo.inspector }}</view>
        </view>
      </view> -->
      <!-- <view class="cu-form-group">
        <view class="title"><text class="cuIcon-favorfill text-xs text-red"></text>巡检日期</view>
        <picker
          mode="date"
          :value="dataInfo.inspectiondate"
          @change="DateChange('inspectiondate',$event)"
        >
          <view class="picker">
            {{
              dataInfo.inspectiondate
                ? dataInfo.inspectiondate
                : "请选择巡检日期"
            }}
          </view>
        </picker>
      </view> -->

      <!-- <view class="cu-form-group" style="min-height: 0"></view>
      <view class="cu-bar bg-white">
        <view class="action">巡检备注</view>
      </view>

      <view class="cu-form-group">
        <textarea
          maxlength="-1"
          v-model="dataInfo.remarks"
          :disabled="modalName != null"
          @input="textareaAInput(dataInfo,$event)"
          placeholder="请输入巡检备注"
        ></textarea>
      </view> -->
	  <view class="cu-form-group " style="margin-top: 10px;">
	      <view class="title"><text class="cuIcon-favorfill text-xs text-red"></text>验收方式</view>
	      <view>
	  		<js-select v-model="dataInfo.canfilecheck" dict-type="zf_ys_type" placeholder="请选择验收方式" class="input-align"></js-select>
	  	</view>
	  </view>
	  <view class="cu-form-group ">
	      <view class="title"><text class="cuIcon-favorfill text-xs text-red"></text>负责人名称</view>
	      <view>
	  		<js-select v-model="dataInfo.usercodepre" :items="userSelectList" placeholder="请选择人员" :tree="true"
	  			:label-value="dataInfo.usernamepre" @label-input="dataInfo.usernamepre = $event"></js-select>
	  	</view>
	  </view>

      <view class="cu-form-group" style="min-height: 0"></view>
      <view class="cu-bar bg-white">
        <view class="action"><text class="cuIcon-favorfill text-xs text-red"></text>验收图片</view>
      </view>
      <view class="cu-form-group">
        <!-- <js-uploadfile
            maxCount="0"
            :biz-key="dataInfo.id"
            biz-type="pmInspection_image"
          ></js-uploadfile> -->
        <js-uploadfile
          v-model="dataInfo.dataMap"
          :biz-key="dataInfo.id"
          biz-type="PmPreAcceptance_image"
        ></js-uploadfile>
      </view>


      <view class="cu-card">
        <view
          class="cu-item shadow "
          v-for="(item, index) in dataInfo.pmRectificationList"
          :key="index"
          v-if="item.status != 1"
          :id="'item-' + index"
        >
          <view class="cu-form-group">
            <view class="title">          
              <view style=" display: inline-block;padding: 5px;background: #3E97B0;color: #fff;width: 40px;text-align: center;font-style: italic;font-weight: bold" class="margin-right-sm">
                {{ index + 1 }}
              </view>整改项
            </view>
            <view>{{ item.rectificationmeasures }}</view>
          </view>
          <view class="cu-form-group" style="min-height: 0"></view>
          <view class="cu-bar bg-white">
            <view class="action text-black"><text class="cuIcon-favorfill text-xs text-red"></text>整改内容</view>
          </view>
          <view class="cu-form-group">
            <textarea
              maxlength="-1"
              :disabled="modalName != null"
              @input="textareaAInput(item,$event)"
              placeholder="整改内容"
              v-model="item.rectificationcontent"
            ></textarea>
          </view>
          <view class="cu-form-group">
            <view class="title"><text class="cuIcon-favorfill text-xs text-red"></text>整改期限</view>
            <view><picker mode="date" :value="item.endtime ? item.endtime : date" start="2015-09-01" @change="DateChange('endtime',$event,item)">
                                <view class="picker">
                                    {{item.endtime ? item.endtime : '请选择整改期限'}}
                                </view>
                            </picker></view>
          </view>
          <view class="cu-form-group padding">
            <view class="title"><text class="cuIcon-favorfill text-xs text-red"></text>图片上传</view>
          </view>
          <view class="cu-form-group">
            <js-uploadfile
              v-if="uploadFile"
              v-model="item.dataMap"
              :biz-key="item.id ==  undefined ? ' ' : item.id"
              biz-type="rectList_file"
              style="width: 100%"
            ></js-uploadfile>
          </view>
          <view class="cu-bar bg-white">
            <view class="action"></view>
            <view>
              <text
                class="cuIcon-deletefill padding text-sl text-red"
                @tap="DelItem(item.pmid?item.pmid:item.id)" 
              ></text>
            </view>
          </view>
        </view>
      </view>
      <view style="height: 180rpx"></view>
      <view class="btn-group cu-bar foot cu-bar1" v-if="showButton">
        <button class="cu-btn  shadow-blur" @click="addDetail($event)">
          <text class="cuIcon-roundadd padding text-red text-xsl"></text>整改项
        </button>
        <button class="cu-btn bg-green shadow-blur" @click="confirm" v-if="flag">
          提交
        </button>
      </view>
    </form>
    <add-detail
      :modalNameDetail="modalNameDetail"
      @modalNameDetailEmit="modalNameDetailEmit"
      v-if="showAddDetail"
      @dInfoItemEmit="dInfoItemEmit"
      :dInfoItem="dInfoItem"
    ></add-detail>
  </view>
</template>
<script>
import addDetail from "./addDetail.vue";
import xmInfo from "@/pages/zfgs/index/componetns/xmInfo.vue";
import {hasPermission} from '@/common/fire.js'
export default {
  components: {
    addDetail,
    xmInfo,
  },
  data() {
    return {
		userSelectList: [],
      date: "2024-03-12",
      modalName: null,
      modalNameDetail: null,
      showAddDetail: false,
      dataInfo: {
        inspectiondate: "",
      },
      dInfoItem: {},
      showButton: true,
      uploadFile: true,
      flag: hasPermission('accept:pre:pmPreacceptance:edit'),
      isSubmitting: false,
      x: 650, //x坐标
      y: 650, //y坐标
    };
    
  },
  onReady() {
  	// 人员和机构数据
  	this.$u.api.office.treeData({isLoadUser: true}).then(res => {
  		this.userSelectList = res;
  	});
  },
  onLoad(e) {

    if (!!e.id) {
      this.showButton = true;
      this.getXjPmInspectionForm(e.id);
    }
    if (!!e.xm) {
      this.showButton = true;
      this.dataInfo = JSON.parse(e.xm);
	   this.dataInfo.projectname = this.dataInfo.name
      //   巡检人
      this.dataInfo.inspector = this.vuex_user.userName;
    }
  },
  methods: {
    getXjPmInspectionForm(id) {
      this.$u.api.zfgs
        .prePmConnectwaterjobForm({
          id: id,
        })
        .then((res) => {
          console.log(res, "res===");
          this.dataInfo = res.pmInspection;
        });
    },
    DateChange(item,e,xmItem) {
      console.log(e.detail.value);
      //   this.dataInfo.inspectiondate = e.detail.value;
      //   更改巡检日期响应式
      if(item === 'inspectiondate'){
        this.$set(this.dataInfo, "inspectiondate", e.detail.value);
      }else{
        xmItem.endtime = e.detail.value;
      }
      
    },
    textareaAInput(item,e) {
      console.log(e,'e===',item);
      if(item.rectificationcontent == undefined){
        this.$set(item, "remarks", e.detail.value);
      }else{
        this.$set(item, "rectificationcontent", e.detail.value);
      }
    },
    addDetail(item, e) {
      // 点击添加往this.dataInfo.pmRectificationList 首位添加
      this.dInfoItem = {
        rectificationcontent: "",
        rectificationmeasures: "现场整改",
        endtime: '',
        dataMap:{},
        // id 为当前时间戳
        xjid: new Date().getTime(),
        pmid: new Date().getTime(),
      };
      if(this.dataInfo.pmRectificationList === undefined){
        this.dataInfo.pmRectificationList = [];
        this.dataInfo.pmRectificationList.push(this.dInfoItem);
      }else{
        this.dataInfo.pmRectificationList.push(this.dInfoItem);
      }
      this.$forceUpdate();
      this.scrollToBottom();
      
      console.log(this.dataInfo.pmRectificationList);

    },
    scrollToBottom() {
      this.$nextTick(() => {
        // 获取最后一个整改项元素的ID
        const lastItemId = `item-${this.dataInfo.pmRectificationList.length - 1}`;

        uni.createSelectorQuery()
          .in(this) // 确保查询在当前组件上下文中执行
          .select(`#${lastItemId}`)
          .boundingClientRect(rect => {
            if (rect) {
              // 滚动到该元素底部，考虑一些额外的偏移量以确保可见
              uni.pageScrollTo({
                scrollTop: rect.bottom + 500, // 可能需要根据实际情况调整偏移量
                duration: 300,
              });
            } else {
              console.warn('无法找到指定的元素:', lastItemId);
            }
          })
          .exec();
      });
    },
    modalNameDetailEmit(e) {
      this.modalNameDetail = e;
      this.uploadFile = false;

      setTimeout(() => {
        this.uploadFile = true;
        console.log(this.uploadFile);
      }, 500);
    },
    dInfoItemEmit(e) {
      if (this.dataInfo.pmRectificationList == undefined) {
        this.dataInfo.pmRectificationList = [];
      }

      if (this.dataInfo.pmRectificationList.length == 0) {
        this.dataInfo.pmRectificationList.push(e);
      } else {
        this.dataInfo.pmRectificationList.map((item) => {
          // 如果item.id == e.id 则替换
          if (item.id == e.id) {
            item = e;
          } else {
            console.log(e);
            this.dataInfo.pmRectificationList.push(e);
          }
        });
      }

      console.log(this.dataInfo.pmRectificationList, e);
    },

    confirm() {
	  if(!this.dataInfo.canfilecheck){
	    this.$u.toast("验收方式必填");
	    return;
	  }
	  if(!this.dataInfo.usercodepre){
	    this.$u.toast("负责人名称必填");
	    return;
	  }
	  if (!this.dataInfo.dataMap || !this.dataInfo.dataMap.PmPreAcceptance_image) {
	    this.$u.toast("验收图片必传");
	    return;
	  }
      if (this.dataInfo.pmRectificationList && this.dataInfo.pmRectificationList.length > 0) {
        let isValid = true;
        let endTimeValid = true;
        let imgValid = true;
        this.dataInfo.pmRectificationList.forEach((item) => {
          if (!item.rectificationmeasures && item.status != 1) {
            isValid = false;
          }
          if (!item.endtime && item.status != 1) {
            endTimeValid = false;
          }
          if( (!item.dataMap || !item.dataMap.rectList_file)&& item.status != 1){
            imgValid = false;
          }
        });
        if (!isValid) {
          this.$u.toast("整改措施必填");
          return;
        }
        if (!endTimeValid) {
          this.$u.toast("整改期限必选");
          return;
        }
        if (!imgValid) {
          this.$u.toast("整改文件必传");
          return;
        }
      }
      if (this.isSubmitting) {
        return;
      } else {
        this.isSubmitting = true;
        try {
          this.$u.api.zfgs.pmPreacceptanceSave(this.dataInfo).then((res) => {
        if (res.result == "true") {
          this.$u.toast(res.message);
          const itemContent = {
            projectno: this.dataInfo.projectno,
            projectname: this.dataInfo.name,
          };
          setTimeout(() => {
            // uni.navigateTo({
            //   url:
            //     "/pages/zfgs/proj/xj/pmInspection/list?item=" +
            //     JSON.stringify(itemContent),
            // });
			uni.navigateBack({
			  delta: 1,
			});
          }, 500);
        }else{
          this.$u.toast(res.message);
        }
      });
        } catch (error) {
          this.$u.toast(error.message);
        } finally {
          this.isSubmitting = false;
        }
      }

    },
    DelItem(pmid) {
      uni.showModal({
        title: "",
        content: "确定要删除吗？",
        cancelText: "取消",
        confirmText: "确认",
        success: (res) => {
          if (res.confirm) {
            // 根据item.zhengGaiNo 查找要删除的项
            // let index = this.dataInfo.pmRectificationList.findIndex(
            //   (item) => item.id == items.id
            // );
            this.dataInfo.pmRectificationList.map((item) => {
              // if (item.id == pmid) {
              //   item.status = 1; //状态为1删除
              //   // 深度监听dataInfo.rectList
              // }
              if (item.pmid == pmid) {
                item.status = 1; //状态为1删除
                // 深度监听dataInfo.rectList
              }else if(item.id == pmid){
                item.status = 1;
              }
            });
            this.$forceUpdate();
            this.$u.toast("删除成功");
          }
        },
      });
    },
    imgListChange(e) {
      this.dataInfo.dImageList = e;
    },
  },
};
</script>
<style lang="scss" scoped>
$all_width: 140rpx;
$all_height: 140rpx;
.movable-area {
  z-index: 999;
  height: 97vh;
  width: 650rpx;
  // max-width: 1152rpx;
  // 固定在右边
  top: -260rpx;
  position: fixed;
  right: $all_width;
  // 固定在右下角
  pointer-events: none; //此处要加，鼠标事件可以渗透
  .movable-view {
    width: $all_width;
    height: $all_height;
    pointer-events: auto; //恢复鼠标事件
    .cu-bar{
      width: 320rpx;
    }
  }
}
.action {
  color: #303133;
}
.cu-form-group {
  flex-wrap: wrap;
}
.cu-bar1 {
  min-height: 80px;
}
.cu-btn {
  font-size: 16px;
  height: 40px;
}
.foot {
  z-index: 997;
  background: #fff;
}
.flex-end {
  display: flex;
  justify-content: flex-end;
}
.text-sl {
  font-size: 22px !important;
}
.text-xsl {
  font-size: 60rpx !important;
}
.sub-title {
  flex-grow: 1; /* 让右侧内容占据剩余空间 */
  max-width: 200px; /* 或其他合适的最大宽度，超过这个宽度时内容会换行 */
  word-break: break-word; /* 或 overflow-wrap: break-word; 允许单词在必要时断开以适应宽度 */
}
.xm-title {
  flex-basis: 100px; /* 或其他合适的固定宽度，用于左侧标题 */
  flex-shrink: 0; /* 防止标题在小屏幕下收缩 */
  overflow: hidden; /* 可选，防止内容溢出 */
}
.text-xs {
  font-size: 18rpx !important;
}
.cu-item{
  border:1px solid #0081ff;
}
</style>